//
//  XJHBaseViewController.swift
//  PublicPod
//
//  Created by 许俊华 on 2021/9/7.
//

import UIKit
import IQKeyboardManagerSwift

open class XJHBaseViewController: UIViewController {

    open lazy var mCollectionFlowLayout:UICollectionViewFlowLayout = {
        var layout:UICollectionViewFlowLayout = UICollectionViewFlowLayout.init()
        return layout
    }()
    
    open lazy var mCollectionView: UICollectionView = {
        var _collectionView: UICollectionView = UICollectionView.init(frame: CGRect.zero, collectionViewLayout: self.mCollectionFlowLayout)
        _collectionView.delegate = self
        _collectionView.dataSource = self
        _collectionView.register(UICollectionViewCell.classForCoder(), forCellWithReuseIdentifier: NSStringFromClass(UICollectionViewCell.classForCoder()))
        _collectionView.backgroundColor = .clear
        return _collectionView
    }()
        
    open lazy var mTableView:UITableView = {
        var _tableView:UITableView = UITableView.init(frame: CGRect.zero, style: UITableView.Style.grouped)
        _tableView.backgroundColor = UIColor.clear
        _tableView.separatorStyle = UITableViewCell.SeparatorStyle.none
        _tableView.delegate = self
        _tableView.dataSource = self
        _tableView.showsVerticalScrollIndicator = false
        _tableView.register(UITableViewCell.classForCoder(), forCellReuseIdentifier: NSStringFromClass(UITableViewCell.classForCoder()))
        return _tableView
    }()
    

    open var mDataArray:[Any] = [Any]()
    open var mParams:[String:Any] = [String:Any]()

    open lazy var mScrollView:UIScrollView = {
        var _scrollView:UIScrollView = UIScrollView.init()
        _scrollView.showsVerticalScrollIndicator = false
        _scrollView.showsHorizontalScrollIndicator = false
        return _scrollView
    }()

    // MARK:自定义导航栏
    open lazy var navBarView:XJHNavView = {
        var _navBarView = XJHNavView.init(frame: CGRect.init(x: 0, y: 0, width: SCREEN_WIDTH, height: NAVIGATIONBAR_HEIGHT))
        return _navBarView
    }()

    open override func viewWillAppear(_ animated: Bool) {
        super.viewWillAppear(animated)
        IQKeyboardManager.shared.enable = false
        IQKeyboardManager.shared.shouldResignOnTouchOutside = false
        IQKeyboardManager.shared.enableAutoToolbar = false
    }
    
    open override func viewDidLoad() {
        super.viewDidLoad()

        // Do any additional setup after loading the view.
        self.view.backgroundColor = UIColor.colorWithHexColor(hexadecimal: "#F6F7F9");
        extendedLayoutIncludesOpaqueBars = true;
        
        if #available(iOS 11.0, *) {
            mScrollView.contentInsetAdjustmentBehavior = .never
            UITableView.appearance().contentInsetAdjustmentBehavior = .never
            UITableView.appearance().sectionHeaderHeight = 0
            UITableView.appearance().sectionFooterHeight = 0
            
            mCollectionView.contentInsetAdjustmentBehavior = .never
        } else {
            automaticallyAdjustsScrollViewInsets = false
        }
        
        
        self.navigationController?.setNavigationBarHidden(true, animated: false)
        
        initSubViews()
        
        self.setNeedsStatusBarAppearanceUpdate()
        
        openSlideSwipPop()
    }
    
    // MARK: 侧滑返回
    open func openSlideSwipPop() -> Void {
        let swipe:UISwipeGestureRecognizer = UISwipeGestureRecognizer(target: self, action: #selector(swipeAction))
        self.view.addGestureRecognizer(swipe)
    }
    
    @objc open func swipeAction() -> Void {
        self.navigationController?.popViewController(animated: true)
    }
    
    // MARK: 展示导航栏阴影
    open func showNavViewShadow() -> Void {
        self.view.layoutIfNeeded()
        self.navBarView.setShadow(sColor: UIColor.colorWithHexColor(hexadecimal: "#F6F7F9"), offset: CGSize(width: 0, height: 2), opacity: 1, radius: 2, cornerSize: 0)
    }
    
    // MARK:设置状态栏文字颜色
    open override var preferredStatusBarStyle: UIStatusBarStyle {
        return .lightContent
    }

    // 初始化导航栏
    func initSubViews() {
        self.view.addSubview(navBarView)
        navBarView.navLeftBtnActionBlock = {() in
            self.swipeAction()
        }
        navBarView.navRightBtnActionBlock = {
            
        }
        
        if self.navigationController != nil {
            if (self.navigationController?.viewControllers.count)! > 1 {
                navBarView.navLeftBtnTitle = "ic_nav_back.png";
            }
        }
        
    }

    // 隐藏导航栏
    open func hideNavBar() -> Void {
        navBarView.isHidden = true
    }
    
    // 展示导航栏
    open func showNavBar() -> Void {
        navBarView.isHidden = false
    }

    // 隐藏返回按钮
    open func hideNavBackBtn() {
        navBarView.navLeftBtn.isHidden = true
    }

    // MARK: presentViewController
    // 目的是为了解决present时，跳转慢的问题，由此推断，presentViewController这个方法有可能不是在UI线程执行的。
    open override func present(_ viewControllerToPresent: UIViewController, animated flag: Bool, completion: (() -> Void)? = nil) {
        DispatchQueue.global(qos: .userInitiated).async {
            // back to the main thread
            self.dispatchMainQueue {
                if #available(iOS 13.0, *) {
                    viewControllerToPresent.modalPresentationStyle = .fullScreen
                }
                super.present(viewControllerToPresent, animated: flag, completion: {
                    
                })
            }
        }
    }


    // MARK: 延迟几秒执行
    open func dispatchAsyncAfter(second:Double, completion:(()->Void)?) {
        DispatchQueue.main.asyncAfter(deadline: DispatchTime.now() + second) {
            completion!()
        }
    }

    // MARK: 主线程
    open func dispatchMainQueue(completion:(()->Void)?) -> Void {
        DispatchQueue.main.async(execute: completion!)
    }
    

    /*
    // MARK: - Navigation

    // In a storyboard-based application, you will often want to do a little preparation before navigation
    override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
        // Get the new view controller using segue.destination.
        // Pass the selected object to the new view controller.
    }
    */

}

extension XJHBaseViewController : UITableViewDelegate, UITableViewDataSource {
    // MARK: UITableView-----------delegate
    open func numberOfSections(in tableView: UITableView) -> Int {
        return 1
    }
    open func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return self.mDataArray.count
    }

    open func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let cell:UITableViewCell = tableView.dequeueReusableCell(withIdentifier: NSStringFromClass(UITableViewCell.classForCoder()))!
        
        return cell
    }
    
    open func tableView(_ tableView: UITableView, heightForFooterInSection section: Int) -> CGFloat {
        return 0.001
    }
    
    open func tableView(_ tableView: UITableView, viewForFooterInSection section: Int) -> UIView? {
        let footerView:UIView = UIView()
        footerView.backgroundColor = .clear
        return footerView
    }
    
    open func tableView(_ tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat {
        return 0.001
    }
    
    open func tableView(_ tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? {
        let headerView:UIView = UIView()
        headerView.backgroundColor = .clear
        return headerView
    }
}

extension XJHBaseViewController : UICollectionViewDelegate, UICollectionViewDataSource, UICollectionViewDelegateFlowLayout {
    
    // MARK: UICollectionView-----------delegate
    open func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        return mDataArray.count
    }

    open func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
        let cell:UICollectionViewCell = collectionView.dequeueReusableCell(withReuseIdentifier: NSStringFromClass(UICollectionViewCell.classForCoder()), for: indexPath)
        
        
        return cell
    }
}
